package com.taikang.hmp.hbusiness.diabetes.measure.meal.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.taikang.hmp.frame.common.datastructre.Dto;
import com.taikang.hmp.frame.common.datastructre.support.BaseDto;
import com.taikang.hmp.frame.common.service.impl.BaseServiceImpl;
import com.taikang.hmp.frame.customer.bean.CustomerInfo;
import com.taikang.hmp.hbusiness.diabetes.measure.hemoglobin.bean.Hemoglobin;
import com.taikang.hmp.hbusiness.diabetes.measure.meal.bean.DayMealAmount;
import com.taikang.hmp.hbusiness.diabetes.measure.meal.bean.Meal;
import com.taikang.hmp.hbusiness.diabetes.measure.meal.bean.MealDetail;
import com.taikang.hmp.hbusiness.diabetes.measure.meal.bean.MealStandard;
import com.taikang.hmp.hbusiness.diabetes.measure.meal.bean.PagodaBean;
import com.taikang.hmp.hbusiness.diabetes.measure.meal.service.IMealService;
import com.taikang.hmp.hbusiness.diabetes.measure.meal.service.MealUtil;
import com.taikang.hmp.hbusiness.diabetes.measure.sugar.bean.Sugar;

/** 
 * 膳食
 * author:qrp
 * time:2015年8月5日 上午11:08:05
 */
public class MealServiceImpl extends BaseServiceImpl implements IMealService{

	public String saveMeal(Dto paramDto){
		Meal meal = new Meal();
		meal.setCustomer_id(paramDto.getAsString("customerid"));
		String querydate = paramDto.getAsString("date").substring(0,10);
		meal.setDate(querydate);
		meal.setEattype_cd(paramDto.getAsString("eattypecd"));
		//删除膳食同一天同一时段信息，以确保同条件单一
		//List<Meal> info = super.getNewDao().queryForList("meal_space.getIsExitMeal", meal);
		super.getNewDao().delete("meal_space.delete_hasmeal", meal);
//		if(info.size() > 0){
//			super.getNewDao().delete("meal_space.delete_meal", info.get(0).getRecord_id());
//			super.getNewDao().delete("meal_space.delete_mealDetail", info.get(0).getRecord_id());
//		}
		String date = paramDto.getAsString("date");
		meal.setDate(date);
		String record_id = java.util.UUID.randomUUID().toString();
		meal.setRecord_id(record_id);
		meal.setSource_cd(paramDto.getAsString("requestsource"));
		meal.setOperater(paramDto.getAsString("uid"));
		meal.setOperate_date(new Date());
		super.getNewDao().insert("meal_space.insert_meal", meal);
		List<Dto> lsit = paramDto.getAsList("mealdetail");
		
		for (int i = 0; i < lsit.size(); i++) {
			MealDetail detail = new MealDetail();
			Dto mealList = (Dto) lsit.get(i);
			String record_detail_id = java.util.UUID.randomUUID().toString();
			detail.setRecord_id(record_detail_id);
			detail.setMeal_id(record_id);
			detail.setDate(date);
			detail.setMealtype_cd(mealList.getAsString("mealtypecd"));
			detail.setValue(mealList.getAsString("value"));
			detail.setVunit(mealList.getAsString("unit"));
			detail.setSource_cd(paramDto.getAsString("requestsource"));
			detail.setOperater(paramDto.getAsString("uid"));
			detail.setOperate_date(new Date());
			super.getNewDao().insert("meal_space.insert_meal_detail", detail);
		}
		//返回评判结果
		String mealWords = null;
		return mealWords;
	}

	public Dto getMealList(Dto paramDto) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("customerid", paramDto.getAsString("customerid"));
		map.put("date", paramDto.getAsString("date"));// 执行日期
		
		if(paramDto.getAsString("eattypecd").equals("")){
			map.put("eattype_cd", null);// 时段
		}else{
			map.put("eattype_cd", paramDto.getAsString("eattypecd"));// 时段
		}
		List<Meal> info = super.getNewDao().queryForList("meal_space.getMeal", map);
		Dto resultMap = new BaseDto();
		Dto result = new BaseDto();
		if (info.size() > 0) {
			result.put("date", info.get(0).getDate());// 执行日期
			result.put("eattypecd", info.get(0).getEattype_cd());// 时段类别
			result.put("calorie", info.get(0).getCalorie());// 消耗卡路里
			// 拼接膳食列表
			List<MealDetail> info1 = super.getNewDao().queryForList(
					"meal_space.getMealDetail", info.get(0).getRecord_id());
			List<Dto> detailList = new ArrayList<Dto>();
			for (int j = 0; j < info1.size(); j++) {
				Dto mealList = new BaseDto();
				mealList.put("mealtypecd", info1.get(j).getMealtype_cd());// 饮食类别
				mealList.put("value", info1.get(j).getValue());// 数量
				mealList.put("unit", info1.get(j).getVunit());// 单位
				detailList.add(mealList);
			}
			resultMap.put("result", result);
			resultMap.put("detailList", detailList);
		}
		return resultMap;
	}

	public Dto getDayMealList(Dto paramDto) {
		Map<String, String> map = new HashMap<String, String>();
		String customerid = paramDto.getAsString("customerid");
		map.put("customerid", customerid);
		map.put("date", paramDto.getAsString("date"));// 执行日期
		//List<Meal> info = super.getNewDao().queryForList("meal_space.getDayMeal", map);
		Dto resultMap = new BaseDto();
		Dto result = new BaseDto();
		List<Dto> detailList = new ArrayList<Dto>();
		//if (info.size() > 0) {
			result.put("directMsg", "");// 膳食合理性评价
			result.put("calorie", 0);// 消耗卡路里
			// 计算每天膳食各类总计
			//此处屏蔽原来的循环方法，直接使用sql查询当天的饮食摄入总量，返回两个字段mealtype_cd 跟  value  返回结果保存在info1
			/*MealDetail detail = new MealDetail();
			List<MealDetail> trueMeal = new ArrayList<MealDetail>(10);
			List<MealDetail> info1 = null;
			for(int i=0;i<info.size();i++){
				info1 = dao.findAllByString("meal_space.getMealDetail", info.get(i).getRecord_id());// 实际膳食摄入量
				for(int k=0;k<info1.size();k++){
					Float temp = Float.parseFloat(trueMeal.get(k).getValue()) + Float.parseFloat(info1.get(k).getValue());
					
					detail = info1.get(k);
					detail.setValue(temp.toString());
					info1.set(k, detail);
					//trueMeal.get(k).setValue(info1.get(k).getValue());
				}
			}*/
			List<DayMealAmount> info1 = null;
			info1 = super.getNewDao().queryForList("meal_space.getDayMealAmount", map);
			List<MealStandard> info2 = super.getNewDao().queryForList("meal_space.getStandard", customerid);// 建议膳食摄入量
			if (info2.size() == 0) {
				try {
					this.initMealStandard2DB(paramDto);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			info2 = super.getNewDao().queryForList("meal_space.getStandard", customerid);// 建议膳食摄入量
			for (int j = 0; j < info1.size(); j++) {
				Dto mealList = new BaseDto();
				mealList.put("mealTypeCd", info1.get(j).getMealtype_cd());// 饮食类别
				// 依次判断其合理性（0,1,2,3-未输入，合理，比较合理，不合理）
				String value = "0";
				
				if (info1.get(j).getValue() == null || info1.get(j).getValue().equals("0")) {
					value = "0";
				} else{
					double realvalue = Double.parseDouble(info1.get(j).getValue());
					double calvalue = Double.parseDouble(info2.get(j).getValue());
					double temresult = realvalue/calvalue;
					if(temresult<1.01 && temresult>0.99){
						value = "1";
					}else if(temresult<1.2001 && temresult>0.7999){
						value = "2";
					}else{
						value = "3";
					}
				}
				mealList.put("value", value);
				detailList.add(mealList);
			}
		//}
		resultMap.put("result", result);
		resultMap.put("detailList", detailList);
		return resultMap;
	}

	public Dto getDayStandardMealList(Dto paramDto) {
		String customerid = paramDto.getAsString("customerid");
//		String date = jsonObj.getString("date");//暂时没有用到
		List<MealStandard> info = super.getNewDao().queryForList("meal_space.getStandard", customerid);
		if(info.size() == 0){
			try {
				this.initMealStandard2DB(paramDto);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		info = super.getNewDao().queryForList("meal_space.getStandard", customerid);
		List<Dto> standardList = new ArrayList<Dto>();
		Dto resultMap = new BaseDto();
		MealStandard standard = null;
		Dto result = new BaseDto();
		if (info.size() > 0) {
			result.put("directmsg", "");// 膳食合理性评价
			result.put("calorie", "0");// 消耗卡路里
			for (int i = 0; i < info.size(); i++) {
				standard = info.get(i);
				// 拼装成文档设计格式返回
				Dto map = new BaseDto();
				map.put("mealtypeCd", standard.getMealtype_cd());
				map.put("value", standard.getValue());
				map.put("unit", standard.getVunit());
				standardList.add(map);
			}
		}
		resultMap.put("result", result);
		resultMap.put("resultList", standardList);
		return resultMap;
	}

	public void initMealStandard2DB(Dto paramDto) throws Exception{
		String customerid = paramDto.getAsString("customerid");
		String uid = paramDto.getAsString("uid");
		List<CustomerInfo> customer = super.getNewDao().queryForList("user_space.getCustomer_uid", uid);
		float height = Float.parseFloat(customer.get(0).getHeight());
		float weight = Float.parseFloat(customer.get(0).getWeight());
		String age = MealUtil.getAgeByBirthday(customer.get(0).getBirthday());
		String sex = customer.get(0).getSex();
		// 建议摄入量
		int intake = MealUtil.getRecommendedIntake(sex, height, weight, Integer.parseInt(age));
		// 能量级别
		int EnergyLevel = MealUtil.getEnergyLevel(intake);
		List<PagodaBean> pagoda = MealUtil.initPagoda();
		// 判断是属于哪种用户，取得is_has_fruit的值
		String result = "";
		
		List<MealStandard> info1 = super.getNewDao().queryForList("meal_space.getStandard", customerid);// 建议膳食摄入量
		if (info1.size() > 0) {
			// 获取当天一个月的空腹血糖、餐后两小时血糖列表
			Map<String, String> condition = new HashMap<String, String>();
			condition.put("customerid", customerid);
			Map<String, String> dateResult = MealUtil.getfirstendDay(new Date());
 			condition.put("end_time", dateResult.get("first"));
			condition.put("start_time", dateResult.get("last"));
			List<Sugar> sugar = super.getNewDao().queryForList("sugar_space.getSugarList", condition);// 血糖
			List<String> list1 = new ArrayList<String>();
			for (int i = 0; i < sugar.size(); i++) {
				list1.add(sugar.get(i).getValue());
			}
			List<Hemoglobin> hemoglobin = super.getNewDao().queryForList("hemoglobin_space.getHemoglobinList", condition);// 糖化血红蛋白
			List<String> list2 = new ArrayList<String>();
			for (int j = 0; j < hemoglobin.size(); j++) {
				list2.add(hemoglobin.get(j).getValue());
			}
			result = MealUtil.getRegisterUserFruitResult(list1, list2);
		} else {
			String p1 = "0";
			if(customer.get(0).getSugar() != null && customer.get(0).getSugar().length()>0){
				p1 = customer.get(0).getSugar();
			}
			Float parm1 = Float.parseFloat(p1);
			String p2 = "0";
			if(customer.get(0).getHemoglobin() != null && customer.get(0).getHemoglobin().length()>0){
				p2 = customer.get(0).getHemoglobin();
			}
			Float parm2 = Float.parseFloat(p2);
			result = MealUtil.getNewUserFruitResult(parm1, parm2);
		}
		int is_has_fruit = Integer.parseInt(result);
		PagodaBean info = null;
		for (int i = 0; i < pagoda.size(); i++) {
			if (pagoda.get(i).getIs_has_fruit() == is_has_fruit && pagoda.get(i).getEnergyLevel() == EnergyLevel) {
				info = pagoda.get(i);
			}
		}
		MealStandard standard = new MealStandard();
		String sourcecd = paramDto.getAsString("requestsource");
		standard.setCustomer_id(customerid);
		standard.setDate("");
		//谷类薯及杂豆
		standard.setRecord_id(java.util.UUID.randomUUID().toString());
		standard.setMealtype_cd("9");
		standard.setValue(info.getStaple());
		standard.setSource_cd(sourcecd);
		standard.setOperater(uid);
		super.getNewDao().insert("meal_space.insert_MealStandard2DB", standard);
		//蔬菜类
		standard.setRecord_id(java.util.UUID.randomUUID().toString());
		standard.setMealtype_cd("7");
		standard.setValue(info.getVegetable());
		standard.setSource_cd(sourcecd);
		standard.setOperater(uid);
		super.getNewDao().insert("meal_space.insert_MealStandard2DB", standard);
		//水果类
		standard.setRecord_id(java.util.UUID.randomUUID().toString());
		standard.setMealtype_cd("8");
		standard.setValue(info.getFruit());
		standard.setSource_cd(sourcecd);
		standard.setOperater(uid);
		super.getNewDao().insert("meal_space.insert_MealStandard2DB", standard);
		//蛋类
		standard.setRecord_id(java.util.UUID.randomUUID().toString());
		standard.setMealtype_cd("6");
		standard.setValue(info.getEgg());
		standard.setSource_cd(sourcecd);
		standard.setOperater(uid);
		super.getNewDao().insert("meal_space.insert_MealStandard2DB", standard);
		//鱼虾类
		standard.setRecord_id(java.util.UUID.randomUUID().toString());
		standard.setMealtype_cd("5");
		standard.setValue(info.getSeafood());
		standard.setSource_cd(sourcecd);
		standard.setOperater(uid);
		super.getNewDao().insert("meal_space.insert_MealStandard2DB", standard);
		//畜禽肉类
		standard.setRecord_id(java.util.UUID.randomUUID().toString());
		standard.setMealtype_cd("4");
		standard.setValue(info.getMeat());
		standard.setSource_cd(sourcecd);
		standard.setOperater(uid);
		super.getNewDao().insert("meal_space.insert_MealStandard2DB", standard);
		// 大豆类及坚果
		standard.setRecord_id(java.util.UUID.randomUUID().toString());
		standard.setMealtype_cd("3");
		standard.setValue(info.getNut());
		standard.setSource_cd(sourcecd);
		standard.setOperater(uid);
		super.getNewDao().insert("meal_space.insert_MealStandard2DB", standard);
		//奶类及奶制品
		standard.setRecord_id(java.util.UUID.randomUUID().toString());
		standard.setMealtype_cd("2");
		standard.setValue(info.getMilk());
		standard.setSource_cd(sourcecd);
		standard.setOperater(uid);
		super.getNewDao().insert("meal_space.insert_MealStandard2DB", standard);
		//油
		standard.setRecord_id(java.util.UUID.randomUUID().toString());
		standard.setMealtype_cd("0");
		standard.setValue(info.getOil());
		standard.setSource_cd(sourcecd);
		standard.setOperater(uid);
		super.getNewDao().insert("meal_space.insert_MealStandard2DB", standard);
		//盐
		standard.setRecord_id(java.util.UUID.randomUUID().toString());
		standard.setMealtype_cd("1");
		standard.setValue(info.getSalt());
		standard.setSource_cd(sourcecd);
		standard.setOperater(uid);
		super.getNewDao().insert("meal_space.insert_MealStandard2DB", standard);
	}

	public List<CustomerInfo> getAllCustomer() {
		return super.getNewDao().queryForList("user_space.getAllUser");
	}
	public void delAllStandardInfo() {
		super.getNewDao().delete("meal_space.delAllStandardInfo", "");
	}
	@Override
	public List<Meal> getMealChart(Dto paramDto)  {
		Meal meal = new Meal();
		meal.setCustomer_id(paramDto.getAsString("customerid"));
		if ("1".equals(paramDto.getAsString("day"))) {
			meal.setDates(paramDto.getAsString("date"));
		} else {
			meal.setBef_date(paramDto.getAsString("befdate") + " 00:00");
			meal.setAft_date(paramDto.getAsString("aftdate") + " 23:59");
		}
		// TODO Auto-generated method stub
		return super.getNewDao().queryForList("meal_space.getMealChart", meal);
	}

	@Override
	public List<Meal> getMealTable(Dto paramDto)  {
		// TODO Auto-generated method stub
		List<Meal> resultList = new ArrayList();
		List<Meal> times = new ArrayList();
		Meal mealRecord = new Meal();
		mealRecord.setCustomer_id(paramDto.getAsString("customerid"));
		if ("1".equals(paramDto.getAsString("day"))) {
			mealRecord.setDates(paramDto.getAsString("date"));
		} else {
			mealRecord.setBef_date(paramDto.getAsString("befdate") + " 00:00");
			mealRecord.setAft_date(paramDto.getAsString("aftdate") + " 23:59");
		}
		times = super.getNewDao().queryForList("meal_space.getMealTable", mealRecord);
		if (times == null) {
			return null;
		} else {
			Meal mealRecordResult = new Meal();
			for (int i = 0; i < times.size(); i++) {
				String j = times.get(i).getEattype_cd();
				boolean flag= false;
				if(i > 0){
					flag = times.get(i).getDates().substring(0, 10).equals(times.get(i-1).getDates().substring(0, 10));
					if(!flag){
						resultList.add(mealRecordResult);
						mealRecordResult = new Meal();
					}
				}
				mealRecordResult.setDates(times.get(i).getDates().substring(0, 10));
					if ("0".equals(j)) {
						if (mealRecordResult.getBreakfast() == null) {
							mealRecordResult.setBreakfast(times.get(i).getCalorie());
						}
					} else if ("1".equals(j)) {
						if (mealRecordResult.getLunch() == null) {
							mealRecordResult.setLunch(times.get(i).getCalorie());
						}
					} else if ("2".equals(j)) {
						if (mealRecordResult.getDinner() == null) {
							mealRecordResult.setDinner(times.get(i).getCalorie());
						}
					} else if ("3".equals(j)) {
						if (mealRecordResult.getSnack() == null) {
							mealRecordResult.setSnack(times.get(i).getCalorie());
						}
					}
					if(i == times.size()-1){
							resultList.add(mealRecordResult);
					}
			}
		}
		return resultList;
	}

	@Override
	public Integer getTargetByUid(Dto paramDto) {
		// TODO Auto-generated method stub

		List<CustomerInfo> customer = super.getNewDao().queryForList("user_space.getCustomer_uid",
				paramDto.getAsString("uid"));
		Integer target = null;
		if (customer != null && customer.get(0).getHeight()!=null) {
			float height = Float.parseFloat(customer.get(0).getHeight());
			float weight = Float.parseFloat(customer.get(0).getWeight());
			Date sysdate = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date birthday = null;
			int age = 0;
			try {
				birthday = sdf.parse(customer.get(0).getBirthday());
				age = sysdate.getYear() - birthday.getYear();
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String sex = customer.get(0).getSex();
			target = MealUtil.getRecommendedIntake(sex, height, weight, age);
		}
		return target;
	}

	public Dto getIsEat(Dto paramDto) {
		List<Dto> info = super.getNewDao().queryForList("meal_space.getIsEat", paramDto);
		Dto dto = new BaseDto();
		if(info.size() == 0){
			dto.put("breakfast", "0");
			dto.put("lunch", "0");
			dto.put("dinner", "0");
			dto.put("add", "0");
		}else{
			String temp = "";
			for(Dto ld : info){
				temp = temp + "#" +ld.getAsString("eattype_cd");
			}
			String[] eat_span = temp.substring(1,temp.length()).split("#");
			//查看早餐是否完成
			if(Arrays.asList(eat_span).contains("0")){
				dto.put("breakfast", "1");
			}else{
				dto.put("breakfast", "0");
			}
			//查看午餐是否完成
			if(Arrays.asList(eat_span).contains("1")){
				dto.put("lunch", "1");
			}else{
				dto.put("lunch", "0");
			}
			//查看晚餐是否完成
			if(Arrays.asList(eat_span).contains("2")){
				dto.put("dinner", "1");
			}else{
				dto.put("dinner", "0");
			}
			//查看加餐是否完成
			if(Arrays.asList(eat_span).contains("3")){
				dto.put("add", "1");
			}else{
				dto.put("add", "0");
			}
		}
		return dto;
	}


}
